package com.zzccyy.jpdemo.page

import android.view.View
import android.widget.ImageView
import android.widget.TextView
import android.widget.Toast
import androidx.core.content.ContextCompat
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.chad.library.adapter.base.BaseQuickAdapter
import com.google.gson.Gson
import com.zzccyy.jpdemo.R
import com.zzccyy.jpdemo.base.BasicBaseActivity
import com.zzccyy.jpdemo.bean.DateInfo
import com.zzccyy.jpdemo.bean.JpBean
import com.zzccyy.jpdemo.bean.SearchListBean
import com.zzccyy.jpdemo.bean.SearchListBean.DataBean.ListBean
import com.zzccyy.jpdemo.dialog.BtDateDialog
import com.zzccyy.jpdemo.utils.DateUtils
import com.zzccyy.jpdemo.utils.DayAdapter
import com.zzccyy.jpdemo.utils.HttpUtils
import com.zzccyy.jpdemo.utils.HttpUtils.HttpCallback
import com.zzccyy.jpdemo.utils.ListAdapter
import com.zzccyy.jpdemo.utils.ListAdapter1
import java.util.Collections


class ResultActivity : BasicBaseActivity(), View.OnClickListener {
    private var ivC: ImageView? = null
    private var recyclerView1: RecyclerView? = null
    private var recyclerView2: RecyclerView? = null
    private var dayAdapter: DayAdapter? = null
    private var listAdapter: ListAdapter? = null
    private var llB: View? = null
    private var rlD: View? = null
    private var start: String? = null
    private var end: String? = null
    private var btDateDialog: BtDateDialog? = null
    private var ttTitle: TextView? = null
    private var ttShow: TextView? = null
    private var ttAll: TextView? = null
    private var listAdapter1: ListAdapter1? = null
    private var from = 0
    private var lllb1: View? = null
    private var lllb2: View? = null
    private var lllb3: View? = null
    private var list: List<ListBean>? = null


    override val layoutId: Int
        get() = R.layout.activity_result

    override fun findViews() {
        ivC = findViewById(R.id.ivC)
        llB = findViewById(R.id.llB)
        ttAll = findViewById(R.id.ttAll)
        ttShow = findViewById(R.id.ttShow)
        ttTitle = findViewById(R.id.ttTitle)
        recyclerView1 = findViewById(R.id.recyclerView1)
        recyclerView2 = findViewById(R.id.recyclerView2)
        lllb1 = findViewById(R.id.lllb1)
        lllb2 = findViewById(R.id.lllb2)
        lllb3 = findViewById(R.id.lllb3)
        rlD = findViewById(R.id.rlD)

        val linearLayoutManager = LinearLayoutManager(this@ResultActivity)
        linearLayoutManager.orientation = LinearLayoutManager.HORIZONTAL
        recyclerView1!!.setLayoutManager(linearLayoutManager)

        recyclerView2!!.setLayoutManager(LinearLayoutManager(this@ResultActivity))
        dayAdapter = DayAdapter(R.layout.item_day)
        recyclerView1!!.setAdapter(dayAdapter)
    }

    override fun setListener() {
        ivC!!.setOnClickListener(this)
        lllb1!!.setOnClickListener(this)
        lllb2!!.setOnClickListener(this)
        lllb3!!.setOnClickListener(this)
        rlD!!.setOnClickListener(this)
        ttAll!!.setOnClickListener(this)
        ttShow!!.setOnClickListener(this)
        dayAdapter!!.onItemClickListener =
            BaseQuickAdapter.OnItemClickListener { adapter, view, position ->
                for (i in dayAdapter!!.data.indices) {
                    dayAdapter!!.data[i].isSelect = i == position
                }
                dayAdapter!!.notifyDataSetChanged()
                val dateInfo = adapter.data[position] as DateInfo
                val date = dateInfo.date
                if (from == 1) {
                    searchJp(date)
                } else {
                    searchTrain(date)
                }
            }
    }


    override fun onClick(v: View) {
        super.onClick(v)
        when (v.id) {
            R.id.lllb1 -> {
                //价格最低
                val data1 = listAdapter1!!.data
                sortByPriceAsc(data1)
                listAdapter1!!.setNewData(data1)
            }

            R.id.lllb2 -> {
                //出发最早
                val data2 = listAdapter1!!.data
                sortByDepartureTime(data2)
                listAdapter1!!.setNewData(data2)
            }

            R.id.lllb3 -> {
                //耗时最低
                val data3 = listAdapter1!!.data
                sortByCostTime(data3)
                listAdapter1!!.setNewData(data3)
            }

            R.id.ivC -> finish()
            R.id.ttAll -> {
                ttAll!!.setBackgroundResource(R.drawable.bg_5a79ff_c12)
                ttShow!!.setBackgroundResource(R.drawable.bg_ffffff_c12)
                ttAll!!.setTextColor(
                    ContextCompat.getColor(
                        this@ResultActivity,
                        R.color.color_ffffff
                    )
                )
                ttShow!!.setTextColor(
                    ContextCompat.getColor(
                        this@ResultActivity,
                        R.color.color_333333
                    )
                )
                listAdapter1!!.setNewData(list)
            }

            R.id.ttShow -> {
                ttShow!!.setBackgroundResource(R.drawable.bg_5a79ff_c12)
                ttAll!!.setBackgroundResource(R.drawable.bg_ffffff_c12)
                ttShow!!.setTextColor(
                    ContextCompat.getColor(
                        this@ResultActivity,
                        R.color.color_ffffff
                    )
                )
                ttAll!!.setTextColor(
                    ContextCompat.getColor(
                        this@ResultActivity,
                        R.color.color_333333
                    )
                )
                // 筛选逻辑：筛选出至少有一个票种不是"无"的车次
                val filteredList: MutableList<ListBean> = ArrayList()
                for (item in list!!) {
                    var hasAvailableTicket = false
                    for (ticket in item.ticketList!!) {
                        if ("无" != ticket.num) {
                            hasAvailableTicket = true
                            break
                        }
                    }
                    if (hasAvailableTicket) {
                        filteredList.add(item)
                    }
                }
                listAdapter1!!.setNewData(filteredList)
            }

            R.id.rlD -> {
                if (btDateDialog == null) {
                    btDateDialog = BtDateDialog(
                        this@ResultActivity,
                        object : BtDateDialog.OnViewClickListener {
                            override fun setData(data: String?) {
                                val dateRangeInfo = DateUtils.getDateRangeInfo(data, 7)
                                dateRangeInfo[0].isSelect = true
                                dayAdapter!!.setNewData(dateRangeInfo)
                                val data1 = convertDate(data)
                                if (from == 1) {
                                    searchJp(data1)
                                } else {
                                    searchTrain(data1)
                                }
                            }
                        })
                }
                btDateDialog!!.show()
            }
        }
    }


    override fun initData() {
        val intent = intent
        val date = intent.getStringExtra("date")
        start = intent.getStringExtra("start")
        end = intent.getStringExtra("end")
        from = intent.getIntExtra("from", 1)
        val data1 = convertDate(date)
        val dateRangeInfo = DateUtils.getDateRangeInfo(date, 7)
        dateRangeInfo[0].isSelect = true
        dayAdapter!!.setNewData(dateRangeInfo)
        ttTitle!!.text = "$start<>$end"
        if (from == 1) {
            listAdapter = ListAdapter(R.layout.item_result)
            recyclerView2!!.adapter = listAdapter
            llB!!.visibility = View.GONE
            ttShow!!.visibility = View.GONE
            ttAll!!.visibility = View.GONE
            //机票
            searchJp(data1)
        } else {
            listAdapter1 = ListAdapter1(R.layout.item_result1)
            recyclerView2!!.adapter = listAdapter1
            llB!!.visibility = View.VISIBLE
            ttShow!!.visibility = View.VISIBLE
            ttAll!!.visibility = View.VISIBLE
            searchTrain(data1)
        }
    }

    private fun searchJp(data1: String?) {
        showLoading()
        val url = "https://api.tgelia.com/api/train/getAirplane"
        val params: MutableMap<String, String?> = HashMap()
        // params.put("date", tDay.getText().toString());
        params["date"] = data1
        params["start"] = start
        params["end"] = end
        HttpUtils.getInstance().postJson(url, params, object : HttpCallback {
            override fun onSuccess(result: String) {
                dissmissLoading()
                val homeListBean = Gson().fromJson(result, JpBean::class.java)
                if (homeListBean != null && homeListBean.code == 200) {
                    val data = homeListBean.data
                    if (data!!.isEmpty()) {
                        Toast.makeText(this@ResultActivity, "当前日期没数据", Toast.LENGTH_SHORT)
                            .show()
                    }
                    listAdapter!!.setNewData(data)
                } else {
                    Toast.makeText(this@ResultActivity, "当前日期没数据", Toast.LENGTH_SHORT).show()
                }
            }

            override fun onFailure(errorMsg: String) {
                dissmissLoading()
                Toast.makeText(this@ResultActivity, "查询失败", Toast.LENGTH_SHORT).show()
            }
        })
    }

    private fun searchTrain(data1: String?) {
        showLoading()
        val url = "https://api.tgelia.com/api/train/getStation"
        val params: MutableMap<String, String?> = HashMap()
        // params.put("date", tDay.getText().toString());
        params["date"] = convertWithSubstring(data1) //date -> 20251016  date -> 2025-10-16
        params["start"] = start
        params["end"] = end
        HttpUtils.getInstance().postJson(url, params, object : HttpCallback {
            override fun onSuccess(result: String) {
                dissmissLoading()
                val homeListBean = Gson().fromJson(result, SearchListBean::class.java)
                if (homeListBean != null && homeListBean.code == 200) {
                    val data = homeListBean.data
                    list = data!!.list
                    if (list!!.isEmpty()) {
                        Toast.makeText(this@ResultActivity, "当前日期没数据", Toast.LENGTH_SHORT)
                            .show()
                    }
                    listAdapter1!!.setNewData(list)
                } else {
                    Toast.makeText(this@ResultActivity, "当前日期没数据", Toast.LENGTH_SHORT).show()
                }
            }

            override fun onFailure(errorMsg: String) {
                dissmissLoading()
                Toast.makeText(this@ResultActivity, "查询失败", Toast.LENGTH_SHORT).show()
            }
        })
    }

    // 按价格升序排序 (MinPrice)
    private fun sortByPriceAsc(list: List<ListBean>) {
        Collections.sort(list, java.util.Comparator { o1, o2 ->
            try {
                val price1 = o1.minPrice!!.toDouble()
                val price2 = o2.minPrice!!.toDouble()
                return@Comparator java.lang.Double.compare(price1, price2)
            } catch (e: NumberFormatException) {
                return@Comparator 0
            }
        })
    }

    // 按出发时间排序 (Departuretime)
    private fun sortByDepartureTime(list: List<ListBean>) {
        Collections.sort(list) { o1, o2 -> o1.departuretime!!.compareTo(o2.departuretime!!) }
    }

    // 按行程时间排序 (Costtime)
    private fun sortByCostTime(list: List<ListBean>) {
        Collections.sort(list, java.util.Comparator { o1, o2 -> // 提取小时和分钟进行比较
            val time1 = o1.costtime!!.replace("小时", ":").replace("分", "")
            val time2 = o2.costtime!!.replace("小时", ":").replace("分", "")

            val parts1 = time1.split(":".toRegex()).dropLastWhile { it.isEmpty() }.toTypedArray()
            val parts2 = time2.split(":".toRegex()).dropLastWhile { it.isEmpty() }.toTypedArray()
            try {
                val hours1 = parts1[0].toInt()
                val minutes1 = if (parts1.size > 1) parts1[1].toInt() else 0
                val totalMinutes1 = hours1 * 60 + minutes1

                val hours2 = parts2[0].toInt()
                val minutes2 = if (parts2.size > 1) parts2[1].toInt() else 0
                val totalMinutes2 = hours2 * 60 + minutes2

                return@Comparator Integer.compare(totalMinutes1, totalMinutes2)
            } catch (e: NumberFormatException) {
                return@Comparator o1.costtime!!.compareTo(o2.costtime!!)
            }
        })
    }

    companion object {
        private fun convertWithSubstring(original: String?): String {
            // 校验原字符串格式（必须为8位数字）
            if (original == null || original.length != 8) {
                return "输入字符串格式错误，必须是8位数字"
            }
            // 截取年（0-4位）、月（4-6位）、日（6-8位）
            val year = original.substring(0, 4)
            val month = original.substring(4, 6)
            val day = original.substring(6, 8)
            // 拼接成目标格式
            return "$year-$month-$day"
        }

        fun convertDate(dateStr: String?): String {
            // 使用正则表达式提取年月日数字
            val parts =
                dateStr!!.split("[年月日]".toRegex()).dropLastWhile { it.isEmpty() }.toTypedArray()

            // 提取年、月、日（数组前三个元素就是年月日）
            val year = parts[0]
            val month = String.format("%02d", parts[1].toInt())
            val day = String.format("%02d", parts[2].toInt())

            return year + month + day
        }
    }
}